package com.bbex.service.impl;

import com.bbex.constant.Constants;
import com.bbex.entity.*;
import com.bbex.exception.PlatException;
import com.bbex.mapper.*;
import com.bbex.service.*;
import com.bbex.util.SnowFlake;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class HongmengCoinVolumeServiceImpl implements HongmengCoinVolumeService {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HongmengCoinVolumeServiceImpl.class);

    @Autowired
    private  HongmengCoinVolumeDao hongmengCoinVolumeDao;
    @Autowired
    private CoinDao coinDao;
    @Autowired
    private PlatUserDao platUserDao;
    @Autowired
    private HongmengCoinHidVolumeDao hongmengCoinHidVolumeDao;
    @Autowired
    private DictService dictService;
    @Autowired
    private DivideintoLogService divideintoLogService;
    @Autowired
    private CoinVolumeDao coinVolumeDao;

    @Override
    public List<HongmengCoinVolume> findAll(String userId) {
        return hongmengCoinVolumeDao.findAll(userId);
    }

    @Override
    @Transactional
    public void userRoyalty(String userId,String hid,String coinId,String coinName) {
        //查询激活所需HMC数值
        BigDecimal hmc = new BigDecimal(dictService.getDictListByItemCode("HIDScale", "volume").get("dictName").toString());
        //直推层分成比例
        BigDecimal firstScale = new BigDecimal(dictService.getDictListByItemCode("HIDScale", "firstScale").get("dictName").toString());
        //其它层分成比例
        BigDecimal otherScale = new BigDecimal(dictService.getDictListByItemCode("HIDScale", "otherScale").get("dictName").toString());

        /*PlatUser hongmengCoinHidVolume = platUserDao.findByid(userId);
        if(null != hongmengCoinHidVolume){
            throw new PlatException(Constants.USER_ACTIVATE_ERR, "该账户已激活hid");
        }*/
        //查询当前正在激活的用户持有资产
        HongmengCoinVolume hongmengCoinVolume = hongmengCoinVolumeDao.findByUserIdAndCoinId(userId, coinId);
        if(null == hongmengCoinVolume){
            throw new PlatException(Constants.USER_ACTIVATE_ERR, "账户HMC余额不足");
        }
        if(hongmengCoinVolume.getVolume().compareTo(hmc) == -1){
            throw new PlatException(Constants.USER_ACTIVATE_ERR, "账户HMC余额不足");
        }
        BigDecimal subVolume = hongmengCoinVolume.getVolume().subtract(hmc);
        //更新普通持有资产
        long l = hongmengCoinVolumeDao.updateVolume(userId, coinId, subVolume, hongmengCoinVolume.getVersion());
        if(l <= 0){
            throw new PlatException(Constants.USER_ACTIVATE_ERR, "更新HMC持有资产错误");
        }
        //根据推广人hid地址查询推广人信息
        PlatUser hidUser = platUserDao.findByHid(hid);
        if(null != hidUser){
            this.updateHmHidVolime(hidUser.getId(),coinId,coinName,hmc.multiply(firstScale),1,null,userId);
            //查询直推层上层人员
            String[] split = hidUser.getPath().split("/");
            int leng = split.length;
            //判断团队人数是否大于11层,大于11层则将第一个人排除
            int k = 0;
            if(leng>11){
                k=1;
            }
            for (int i = k; i < split.length ; i++) {
                if (i <= split.length - 2) {
                    //查询直推层数量
                    int countByReferid = platUserDao.findCountByReferid(split[i]);
                    //判断当前用户直推人数是否符合相应层级的分成资格
                    if (countByReferid >= leng - i) {
                        this.updateHmHidVolime(split[i], coinId, coinName, hmc.multiply(otherScale), 2, String.valueOf(i),userId);
                    }
                }
                //循环查询团队业绩
                PlatUser byId = platUserDao.findByid(split[i]);
                if (null != byId) {
                    if (StringUtils.isBlank(byId.getTeamNum())) {
                        byId.setTeamNum("1");
                    } else {
                        int teamNum = Integer.parseInt(byId.getTeamNum());
                        teamNum += 1;
                        byId.setTeamNum(String.valueOf(teamNum));
                    }
                    //更新团队业绩
                    long l1 = platUserDao.updateById(byId);
                    if (l1 <= 0) {
                        throw new PlatException(Constants.USER_ACTIVATE_ERR, "更新团队业绩错误");
                    }
                }
            }
            this.saveLog(userId,coinId,coinName,hmc);
            //生成hid账户
            this.hmCoinAdd(userId,coinId,coinName,new BigDecimal(0));
        }else{
            throw new PlatException(Constants.USER_ACTIVATE_ERR, "此hid地址不存在");
        }

    }

    //添加hid资产
    private void hmCoinAdd(String userId,String coin,String coinSymbol,BigDecimal volume) {
        HongmengCoinHidVolume hongmengCoinHidVolume = new HongmengCoinHidVolume();
        hongmengCoinHidVolume.setCoinId(coin);
        hongmengCoinHidVolume.setCoinSymbol(coinSymbol);
        hongmengCoinHidVolume.setFlag(0);
        hongmengCoinHidVolume.setUserId(userId);
        hongmengCoinHidVolume.setCreateDate(LocalDateTime.now());
        hongmengCoinHidVolume.setVolume(volume);
        hongmengCoinHidVolume.setLockVolume(new BigDecimal(0));
        String id = SnowFlake.createSnowFlake().nextIdString();//主键id
        hongmengCoinHidVolume.setId(id);
        hongmengCoinHidVolumeDao.insert(hongmengCoinHidVolume);
    }

    //更新hid资产
    private void updateHmHidVolime(String userId,String coinId,String coinName,BigDecimal volume,Integer type,String level,String sourceId){
        //查询推广人hid钱包持有资产
        HongmengCoinHidVolume hmHidCoinVolume = hongmengCoinHidVolumeDao.findByUserIdAndCoinId(userId, coinId);
        if(null == hmHidCoinVolume){
            //推广人hid资产为空则插入资金
            this.hmCoinAdd(userId,coinId,coinName,volume);
        }else{
            //更新直推层/直推层上层提成资金
            long l = hongmengCoinHidVolumeDao.updateAddVolume(userId, coinId, volume);
            if(l <= 0){
                if(type == 1){
                    throw new PlatException(Constants.USER_ACTIVATE_ERR, "更新直推层资金错误");
                }else{
                    throw new PlatException(Constants.USER_ACTIVATE_ERR, "更新上层资金错误");
                }
            }
        }
        //添加分成记录
        this.saveDivideintoLog(userId,coinId,coinName,volume,type,level,sourceId);
    }

    //记录激活hid花费资金
    private void saveLog(String userId,String coinId,String coinName,BigDecimal hmc){
        //获取用户信息
        PlatUser user = platUserDao.findByid(userId);
        Map map = new HashMap();
        String id = SnowFlake.createSnowFlake().nextIdString();
        map.put("id", id);
        map.put("type", "4");
        map.put("userId", userId);
        map.put("mobile", user.getMobile());
        map.put("mail", user.getMail());
        map.put("coinId", coinId);
        map.put("coinSymbol", coinName);
        map.put("hmVolume", hmc);
        map.put("createDate", new Date());
        map.put("status", "1");
        coinVolumeDao.insertLog(map);
    }

    private void saveDivideintoLog(String userId,String coinId,String coinName,BigDecimal volume,Integer type,String level,String sourceId){
        DivideintoLog divideintoLog = new DivideintoLog();
        String id = SnowFlake.createSnowFlake().nextIdString();
        divideintoLog.setId(id);
        divideintoLog.setCreateDate(LocalDateTime.now());
        divideintoLog.setUserId(userId);
        divideintoLog.setCoinId(coinId);
        divideintoLog.setCoinSymbol(coinName);
        divideintoLog.setVolume(volume);
        divideintoLog.setFeeVolume(new BigDecimal(0));
        divideintoLog.setType(type);
        divideintoLog.setSourceVolume(new BigDecimal(0));
        divideintoLog.setLevel(level);
        divideintoLog.setSourceId(sourceId);

        divideintoLogService.save(divideintoLog);
    }
}
